package com.zbkj.service.service.impl;

import com.zbkj.common.model.admin.SystemAdmin;
import com.zbkj.common.model.agent.AgentConfig;
import com.zbkj.common.model.agent.AgentConfigItems;
import com.zbkj.common.model.agent.UserAgent;
import com.zbkj.common.request.PageParamRequest;
import com.github.pagehelper.PageHelper;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zbkj.common.exception.AppException;
import com.zbkj.common.response.BrandAgentItemsPageDataResponse;
import com.zbkj.common.request.BrandAgentItemsSearchRequest;
import com.zbkj.common.request.BrandAgentItemsSaveRequest;

import com.zbkj.common.result.CommonResultCode;
import com.zbkj.common.utils.CrmebDateUtil;
import com.zbkj.common.model.agent.BrandAgentItems;
import com.zbkj.common.utils.SecurityUtil;
import com.zbkj.common.vo.LoginUserVo;
import com.zbkj.service.dao.BrandAgentItemsDao;
import com.zbkj.service.service.AgentConfigItemsService;
import com.zbkj.service.service.AgentConfigService;
import com.zbkj.service.service.BrandAgentItemsService;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.service.service.UserAgentService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @author dazongzi
* @description BrandAgentConfigItemsServiceImpl 接口实现
* @date 2025-07-01
*/
@Service
public class BrandAgentItemsServiceImpl extends ServiceImpl<BrandAgentItemsDao, BrandAgentItems> implements BrandAgentItemsService {

    @Resource
    private BrandAgentItemsDao dao;
    @Resource
    private UserAgentService userAgentService;
    @Resource
    private AgentConfigItemsService agentConfigItemsService;
    @Resource
    private AgentConfigService agentConfigService;

    @Override
    public Boolean create(BrandAgentItemsSaveRequest brandAgentItemsSaveRequest) {
        BrandAgentItems brandAgentItems = new BrandAgentItems();
        BeanUtils.copyProperties(brandAgentItemsSaveRequest, brandAgentItems, "id");
        boolean save = save(brandAgentItems);
        if (!save) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "添加失败");
        }
        return save;
    }

    /**
     * 分页查询品牌商代理设置明细表
     *
     * @param request          请求参数
     * @param pageParamRequest 分页类参数
     * @return List<BrandAgentConfigItems>
     * @author dazongzi
     * @since 2025-07-01
     */
    @Override
    public List<BrandAgentItemsPageDataResponse> getList(BrandAgentItemsSearchRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        //带 BrandAgentConfigItems 类的多条件查询
        LambdaQueryWrapper<BrandAgentItems> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.orderByDesc(BrandAgentItems::getCreateTime);
        List<BrandAgentItems> brandAgentItemsses = dao.selectList(lambdaQueryWrapper);
        // 添加活动状态
        List<BrandAgentItemsPageDataResponse> brandAgentItemsResponses = new ArrayList<>();

        brandAgentItemsses.stream().forEach(x->{
            BrandAgentItemsPageDataResponse brandAgentConfigItemsResponse = new BrandAgentItemsPageDataResponse();
            BeanUtils.copyProperties(x, brandAgentConfigItemsResponse);
            brandAgentItemsResponses.add(brandAgentConfigItemsResponse);
        });
        return brandAgentItemsResponses;
    }

    @Override
    public List<BrandAgentItems> getListByRegionId(Integer regionId) {
        LambdaQueryWrapper<BrandAgentItems> lqw = Wrappers.lambdaQuery();
        lqw.eq(BrandAgentItems::getIsDel, 0);
        lqw.eq(BrandAgentItems::getAgentReginId, regionId);
        lqw.orderByDesc(BrandAgentItems::getId);
        return this.list(lqw);
    }

    @Override
    public void deleteByRegionId(List<Integer> auditIdList) {
        dao.delete(new LambdaQueryWrapper<BrandAgentItems>().in(BrandAgentItems::getAgentReginId, auditIdList));
    }



    @Override
    public List<BrandAgentItems> getAgentItems(Integer brandId) {
        SystemAdmin systemAdmin =  SecurityUtil.getLoginUserVo().getUser();
        Integer adminId =  systemAdmin.getId();
        String provinceId =null;
        String cityId=null;
        String districtId=null;
        String streetId=null;
        String community=null;
        String tribe=null;
        List<BrandAgentItems> brandAgentItemsList = new ArrayList<>();
        UserAgent userAgent = userAgentService.getAdminUserId(adminId);
        if (userAgent!=null){
            //查上一个等级
            Integer regionType = userAgent.getAgentLevel();
            //代理等级（0:无，1:省,2:市,3:区/县，4:乡/镇/街道，5:社区/村，6：小区）
            if (userAgent.getAgentLevel()==1){
                provinceId = userAgent.getProvinceId();
            }else  if (userAgent.getAgentLevel()==2){
                provinceId = userAgent.getProvinceId();
                cityId = userAgent.getCityId();
            }else if (userAgent.getAgentLevel()==3){
                provinceId = userAgent.getProvinceId();
                cityId = userAgent.getCityId();
                districtId = userAgent.getDistrictId();
            }else if (userAgent.getAgentLevel()==4){
                provinceId = userAgent.getProvinceId();
                cityId = userAgent.getCityId();
                districtId = userAgent.getDistrictId();
                streetId = userAgent.getStreetId();
            }else if (userAgent.getAgentLevel()==5){
                provinceId = userAgent.getProvinceId();
                cityId = userAgent.getCityId();
                districtId = userAgent.getDistrictId();
                streetId = userAgent.getStreetId();
                community = userAgent.getCommunity();
            }else if (userAgent.getAgentLevel()==6){
                provinceId = userAgent.getProvinceId();
                cityId = userAgent.getCityId();
                districtId = userAgent.getDistrictId();
                streetId = userAgent.getStreetId();
                community = userAgent.getCommunity();
                tribe = userAgent.getTribe();
            }
             brandAgentItemsList = dao.getAgentItems(brandId, regionType ,
                    provinceId,
                    cityId,
                    districtId,
                    streetId,
                    community,
                    tribe);

        }else  if (brandAgentItemsList.size()==0 && brandId.equals(adminId)){//证明是品牌商登陆
            Integer targetBrandId =  systemAdmin.getBrandId();
            AgentConfig agentConfig= agentConfigService.getAgentConfigByTargetBrand(targetBrandId);
            if (agentConfig!=null){
                List<AgentConfigItems> agentConfigItemsList = agentConfigItemsService.getListByConfigId(agentConfig.getId());
                List<BrandAgentItems> finalBrandAgentItemsList = brandAgentItemsList;
                agentConfigItemsList.forEach(agentConfigItems -> {
                    BrandAgentItems brandAgentItems = new BrandAgentItems();
                    BeanUtils.copyProperties(agentConfigItems, brandAgentItems);
                    finalBrandAgentItemsList.add(brandAgentItems);
                });
            }

        }

        return brandAgentItemsList;
    }

}

